﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TekaMUD.Engine.Framework;


namespace TekaMUD.Engine.Workers
{
	/// <summary>
	/// Base class for worker threads
	/// </summary>
	public abstract class WorkerThread
	{
		public string Name { get; set; }
		public DateTime ActivationDate { get; set; }
		public DateTime LastRun { get; set; }
		protected TimeSpan Period { get; set; }
		protected Thread thread;
		protected volatile bool Terminated = false;

		public WorkerThread(string name, TimeSpan period)
		{
			Name = name;
			thread = new Thread(new ThreadStart(Run));
			thread.Name = name;
			Period = period;

			Logger.LogDebug("Registered thread: " + name + " every " + period.ToString());
		}

		public WorkerThread(string name)
		{
			Name = name;
			thread = new Thread(new ThreadStart(Run));
			thread.Name = name;

			Logger.LogDebug("Registered thread: " + name);
		}

		public void Start()
		{
			if (thread != null)
				thread.Start();
		}

		public void Terminate()
		{
			Terminated = true;
		}

		public void Abort(bool abortCurrentThread)
		{
			if (thread != null && thread.IsAlive && thread != Thread.CurrentThread && (thread.ThreadState != ThreadState.Aborted && thread.ThreadState != ThreadState.Stopped))
			{
				Logger.LogInfo("Aborting thread " + Name);
				thread.Abort();
			}
		}

		protected virtual void Run()
		{
		}
	}
}
